package com.pay.ioopos.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pay.ioopos.BindState;
import com.pay.ioopos.DataFactory;
import com.pay.ioopos.DeviceUtils;
import com.pay.ioopos.HttpUtil;
import com.pay.ioopos.R;
import com.pay.ioopos.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

public class StatisticsOverviewFragment extends AbstractNetworkFragment implements BindState {
    private static final String TAG = StatisticsOverviewFragment.class.getSimpleName();
    private Handler handler = new Handler();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_statistice_overview, container, false);
    }

    @Override
    protected void execute() throws Exception {
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String sn = DeviceUtils.sn(getActivity());
        String key = DataFactory.getDataStore().getTransKey();
        String serverUrl = DataFactory.getDataStore().getServerUrl();
        String sign = Utils.sha256(sn + timestamp + key);
        JSONObject json = new JSONObject();
        json.put("version", "v2");
        json.put("deviceSn", sn);
        json.put("timestamp", timestamp);
        json.put("sign", sign);
        String jsonString = json.toString();
        jsonString = HttpUtil.post(serverUrl + "/qrpos/api/mch/trade/today/v2", jsonString);
        json = new JSONObject(jsonString);
        if (!json.getString("status").equals("200")) {
            onError("[" + json.getString("status") + "]" + json.getString("message"));
            return;
        }
        JSONObject result = json.getJSONObject("result");
        JSONArray arr = result.getJSONArray("show");
        handler.post(() -> showData(arr));
    }

    private void showData(JSONArray arr) {
        LinearLayout mainLinerLayout = getActivity().findViewById(R.id.stat_container);
        for (int i = 0; i < arr.length(); i++) {
            TextView textView = new TextView(getContext());
            //textView.setHeight(WRAP_CONTENT);
            //textView.setWidth(MATCH_PARENT);
            if (i == 0) {
                textView.setTextSize(35);
            } else {
                textView.setTextSize(30);
            }
            try {
                textView.setText(arr.getString(i));
            } catch (JSONException e) {
                Log.e(TAG, "json异常", e);
                onError(e.getMessage());
            }
            mainLinerLayout.addView(textView);
        }
    }

}
